/**
 * Created by yanyuan on 2014/12/23.
 */
angular.module('myApp.FileHandler', []).
    factory('FileHandler', ['$http','$q', function($http, $q){

        var uploadFile = function(paramData){
            var defered = $q.defer();
            $http({
                method : 'POST',
                url : 'fileOperations/uploadStreamMd5.do',
                data : paramData,
                headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).success(function(data){
                if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                    util.tokenExpire();
                    return;
                }
                if (data.error) {
                    defered.reject(data.error);
                }
                if (data.result == "success") {
                    defered.resolve(data);
                }
            }).error(function(){
                defered.reject("请求服务器失败，请稍后再试！");
            });
            return defered.promise;
        }

        var updateFileForm = function(file){
        	var sname = file.name;
            var defered = $q.defer();
            var fileList = [];
            fileList.push(file);
            var formData = new FormData();
            formData.append('files', fileList[0]);
            $.ajax({
                url: "fileOperations/upload.do?sfile="+sname,
                type: "POST",
                data: formData,
                processData: false,  // 告诉jQuery不要去处理发送的数据
                contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
                success : function(data){
                    if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                        util.tokenExpire();
                        return;
                    }
                    if(data.error){
                        defered.reject(data.error);
                    } 		
                    defered.resolve(data);
                },
                error : function(){
                    defered.reject('文件上传失败！');
                }
            });
            return defered.promise;
        }

        return {
            uploadFile : uploadFile,
            updateFileForm : updateFileForm
        }
    }]);